import Vue from 'vue'
import VueRouter from 'vue-router'
import {getLoginToken} from "../utils/db";
import config from "../config";

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
const routes = [
    {
        path: '/',
        name: 'login',
        meta: {notToken: true},
        component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue')
    },
    {
        path: '/demo',
        name: 'demo',
        meta: {notToken: true},
        component: () => import(/* webpackChunkName: "demo" */ '../views/Demo.vue')
    },
    {
        path: '/home',
        name: 'home',
        component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue')
    },
    {
        path: '*',
        meta: {notToken: true, notFound: true},
        component: () => import(/* webpackChunkName: "other" */ '../views/404.vue')
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
});
router.beforeEach((to, from, next) => {
    let toMeta = to.meta || {}
    if (toMeta.notFound) {
        next();
    }
    const token = getLoginToken();
    if (toMeta.notToken && token) {
        // 放在了Login.vue处理了（可以移过来）
    }
    if (!toMeta.notToken && !token) {
        next({name: config.loginRouteName});
    }
    next();
})

export default router
